<% extends "common/msui.html" %>
<% block title %>产品<% endblock %>
<% block body %>
<% set template = _pool['product.template'].read([id], []) %>
<% set images = _pool['product.template'].get_images(id) %>
<% set evaluation = _pool['product.template'].get_evaluation(id) %>
<% set html = _page.render('homepage') %>
<div class="page" id="page-product" ms-controller="productDetails">
  <header class="bar bar-nav">
    <a class="button button-link button-nav pull-left back" href="/mshop" >
      <span class="icon icon-left"></span>
      返回
    </a>
    <h1 class="title">{{template.name}}</h1>
  </header>
  <div class="content">
    <div>
        <div class="swiper-container product-swiper-container" data-space-between='10'>
            <div class="swiper-wrapper">
                <div class="swiper-slide product-swiper-image" ms-repeat='images' ms-visible='$index < 10'><img ms-attr-src="{{el.image}}" alt=""></div>
            </div>
            <div class="swiper-pagination"></div>
        </div>

        <div class='product-content'>
            <div class='product-header'><span>{{template.name}}</span></div>
            <div class='product-description'><span>{{template.description_sale}}</span></div>
        </div>

        <div class='product-evaluation' ms-if='evaluation'>
            <div class='product-evaluation-header'><span>商品评价({{evaluation.count}})</span></div>

            <div class='product-evaluation-image'>
                <img ms-attr-src='/website/image/res.partner/{{evaluation.user_id}}/image' />
                <span>{{evaluation.username}}</span>
            </div>
            <div class='product-evaluation-content'>
                <div class='product-evaluation-content-info'><span>{{evaluation.description}}</span></div>
                <div class='product-evaluation-content-variants'><span>{{evaluation.variants}}</span></div>
            </div>

            <div class='product-evaluation-btn' ms-click='open_evaluation'>
                <span>查看全部评价</span>
            </div>
        </div>

        <div class='product-no-evaluation' ms-if='!evaluation'><span>暂无评价</span></div>

        <div ms-class='content-mask:choose_product' ></div>

        <div ms-visible='choose_product' style='z-index:12'>
            <div class='card attribute-cart-header'>
                <img ms-attr-src='{{product_info.image_url}}' />
                <div class='attribute-cart-header-info'>
                    <p style='color:red'>¥{{product_info.price_unit}}</p>
                    <p>库存{{product_info.qty_available}}{{product_info.uom}}</p>
                    <div ms-visible='product_info.variant'>
                        <ul><li>已经选择</li><li ms-repeat='attribute' >'{{el.choose.name}}'</li></ul>
                    </div>
                    <div ms-visible='!product_info.variant'>
                        <ul><li>请选择</li><li ms-repeat='attribute' ms-if-loop='!el.choose'>{{el.name}}</li></ul>
                    </div>
                </div>

                <div class='attribute-cart-header-close' ms-click='close_cart'><span>x</span></div>
            </div>
            <div class='card attribute-cart-content'>

                <div class='attribute-cart-sale' ms-visible='product_info.is_group' >
                    <div class='attribute-cart-time'>
                        <div ms-visible='product_info.start_time'><span>开始时间：</span><span>{{product_info.start_time}}</span></div>
                        <div ms-visible='product_info.end_time'><span>结束时间：</span><span>{{product_info.end_time}}</span></div>
                    </div>

                    <div class='attribute-cart-qty'>
                        <div><span>预订/起订数量</span></div>
                        <div><span>{{product_info.reserve_quantity}}/{{product_info.minimum_quantity}}</span></div>
                    </div>
                </div>

                <ul style='padding-left:10px'>
                    <li ms-repeat-line='attribute' style='list-style-type:none'>
                        <div class='attribute-title' >{{line.name}}</div>
                        <ul class='attribute-list'>
                            <li ms-repeat='line.value' class='attribute-value' ms-class-1='attribute-value-choosed:el==line.choose' ms-class-2='attribute-value-disabled:el.disable' ms-click='choose_attribute(line, el)'>
                                {{el.name}}
                            </li>
                        </ul>
                        <hr />
                    </li>
                </ul>

                <div class='row attribute-cart-quantity'>
                    <span>购买数量</span>
                    <div class='product-control-qty'>
                      <span ms-click='mins_qty()' class='product-minus-qty' ms-class='product-minus-qty-disable:product_qty <= 1'>-</span><input class='product-qty' ms-duplex='product_qty' type='text' autocomplete='off' /><span ms-click='plus_qty()' class='product-plus-qty'>+</span>
                    </div>
                </div>
            </div>

            <div class='card attribute-cart-footer' ms-class='attribute-cart-footer-disable:!product_info.variant' ms-click='confirm_product()'>
                <span>确定</span>
            </div>
        </div>

        <div class='card mshop-tab-card' ms-visible='!choose_product'>
            <div class='card-content'>
              <div class='card-content-inner' style='padding-top:0px;padding-bottom:0px'>
                <div class='row'>
                  <div class='col-30 pull-right mshop-clearing' ms-click='prepare_buy_now' style='font-size:14px;padding-left:3px;padding-right:3px'><span>立即购买</span></div>
                  <div class='col-30 pull-right mshop-clearing mshop-buy-now' ms-click='prepare_add_cart' style='font-size:14px;padding-left:3px;padding-right:3px'><span>加入购物车</span></div>

                </div>
              </div>
            </div>
        </div>

    </div>
  </div>

    <script type="application/javascript">
    $(function(){
        //服务端获得的产品json数据
        $(".swiper-container").swiper();

        var template = ${template|tojson|safe};
        var images = ${images|tojson|safe} || [{}]; 
        var evaluation = ${evaluation | tojson | safe};

        $.ajax({
            url: '/mshop/product/get_attribute',
            data: {product_id: template[0].id},
            type: 'get',
            success: function(e) {
                product_vm.attribute = JSON.parse(e);
                refresh_product();
            },
            async: true,
        });

        function simple_all(obj, func) {
            var return_flag = true;
            Array.prototype.forEach.call(obj, function(line) {
                if (!func(line)) {
                    return_flag = false
                }
            });

            return return_flag
        };

        function mixed_array(array, another) {
            return Array.prototype.filter.call(array, function(value) { return another.indexOf(value) != -1 } )
        };

        function reduce_array(array, attribute_id) {
            var reduced_array = []
            array.forEach(function(line) {
                if (line.attribute_id != attribute_id) {
                    reduced_array.push(line.value)
                };
            });

            if (reduced_array.length != 0) {
                return reduced_array.reduce(mixed_array);
            }

            return reduced_array;
        };

        function refresh_product() {

            var attribute_product_choose = [];
            product_vm.attribute.forEach(function(line) {
                line.value.forEach(function(value) {
                    value.disable = false;

                    if (value === line.choose) {
                        attribute_product_choose.push({attribute_id: line.attribute_id, value: value.product});
                    };
                });
            });

            if (attribute_product_choose.length != 0) {
                var mixed_product_choose = {};
                product_vm.attribute.forEach(function(line) {
                    mixed_product_choose[line.attribute_id] = reduce_array(attribute_product_choose, line.attribute_id);
                });

                product_vm.attribute.forEach(function(line) {
                    line.value.forEach(function(value) {
                        var attribute_value = mixed_product_choose[line.attribute_id];
                        if (attribute_value.length != 0) {
                            if ((mixed_array(attribute_value, value.product)).length === 0) {
                                value.disable = true;
                            };
                        };
                    });
                });

            };

            // @正翔 可以尝试这个Array.prototype.every.call(product_vm.attribute, function(index, value) { return value.choose })
            if (simple_all(product_vm.attribute, function(l) {return l.choose})) {
                var attribute = {tmpl_id: product_vm.template.id, 'attributes': []}
                product_vm.attribute.forEach(function(line) {
                    attribute['attributes'].push(line.choose.value_id);
                });

                $.ajax({
                    url: '/mshop/product/get_product_by_attribute',
                    data: {attribute: JSON.stringify(attribute)},
                    type: 'post',
                    success: function(e) {
                        product_vm.product_info = JSON.parse(e);
                        for (var i = 0; i < images.length; i++) {
                            if (images[i].product_id == product_vm.product_info.id) {
                                product_vm.product_info.image_url = images[i].image;
                                break;
                            };
                        };
                    },
                    async: true,
                });
            } else {
                product_vm.product_info = {id: product_vm.template.id, price_unit: product_vm.template.list_price, qty_available: product_vm.template.qty_available, uom: product_vm.template.uom_id[1], variant: false, image_url: images[0].image};
            };
        };

        var product_vm = avalon.define({
            $id: 'productDetails',
            choose_product: false,
            product_info: {id: template[0].id, price_unit: template[0].list_price, qty_available: template[0].qty_available, uom: template[0].uom_id[1], variant: false, image_url: images[0].image},
            current_ids: [],
            template: template[0],
            images: images,
            evaluation: evaluation,
            product_qty: 1,
            buy_now: false,
            // hidden_footer: false,
            attribute: [],
            prepare_add_cart: function() {
                product_vm.choose_product = true;
                product_vm.buy_now = false;
            },
            prepare_buy_now: function() {
                product_vm.choose_product = true;
                product_vm.buy_now = true;
            },
            close_cart: function() {
                product_vm.choose_product = false;
            },
            choose_attribute: function(line, el) {
                if (!el.disable) {
                    line.choose = line.choose == el? false : el;
                    refresh_product();
                };
            },
            mins_qty: function() {
                if (parseInt(product_vm.product_qty) > 1) {
                    product_vm.product_qty = parseInt(product_vm.product_qty) - 1
                }
            },
            plus_qty: function() {
                product_vm.product_qty = parseInt(product_vm.product_qty) + 1
            },
            confirm_product: function() {
                if (product_vm.product_info.variant) {
                    if (product_vm.buy_now && product_vm.product_info.reserve_quantity < product_vm.product_info.minimum_quantity) {
                        $.alert("抱歉，预订数量还没有达到起订数量，请先加入购物车")
                        return;
                    }

                    $.ajax({
                        url: product_vm.buy_now? '/mshop/shopping_cart/buy_now' : '/mshop/shopping_cart/add',
                        data: {product_id: product_vm.product_info.id, add_qty: product_vm.product_qty},
                        type: 'get',
                        success: function(e) {
                            product_vm.product_info.reserve_quantity = parseInt(product_vm.product_info.reserve_quantity) + 
                                parseInt(product_vm.product_qty);
                            if (!product_vm.buy_now) {
                                $.toast("商品已成功添加到购物车");
                            } else {
                                $.router.loadPage('/mshop/order?order_id=' + e);
                            }
                        },
                        async: true,
                    });

                    product_vm.choose_product = false;
                }
            },
            open_evaluation: function() {
                $.router.loadPage('/mshop/product/evaluations?template_id=' + product_vm.template.id)
            },
        });

        avalon.scan();
        $.hideIndicator();
    });

    </script>
    <% endblock %>
</div>